﻿using DLLPC.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using VisionCore;

namespace COER
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private Thread BThread;
        private bool isInitialComplete = false;
        private bool isKernelLoadComplete = false;
        private void MainForm_Load(object sender, EventArgs e)
        {
            this.Text = "Exchange_Motion " + VersionInfo.ver;

            if (this.DesignMode == true)
            {
                return;
            }

            // 系统32位退出
            if (IntPtr.Size == 4)
            {
                return;
            }

            try
            {
                BThread = new Thread(backgroundWork);
                BThread.IsBackground = true;
                BThread.Start();
                WindowState = FormWindowState.Maximized;
                timer1.Start();
            }
            catch (Exception ex)
            {
                LogHelper.Write(LogHelper.Module.Exception, ex.Message);
                LogHelper.Write(LogHelper.Module.Exception, ex.StackTrace);
                MessageBox.Show(ex.Message);
            }

            GetControls(pnlMainOP.Controls);
            GetControls(pnlMain.Controls);
        }

        private void backgroundWork()
        {
            Kernel.KernelInitialization();

            Thread.Sleep(1000);
            isKernelLoadComplete = true;
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Kernel.Quit();
            e.Cancel = true;
            return;
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Kernel.Quit();
        }

        int iRefresh = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (this.DesignMode == true)
            {
                return;
            }

            if (IntPtr.Size == 4)
            {
                return;
            }

            if (isKernelLoadComplete == false) return;

            if (!isInitialComplete && isKernelLoadComplete && Kernel.motion.IsRun)
            {
                isInitialComplete = true;
                if (Kernel.motion.IsRun && Kernel.motion.IsRun)
                {
                    uC_MotionStatus1.Manual_Load();
                }

                uC_LogShow1.ShowEnable();
                uC_RecipeSetting1.ShowForm();
                uC_SystemSetting1.ShowForm();
               
                uC_MainSub1.Manual_Load();
                uC_AixsHomeStatus1.Load();

                this.Enabled = true;
            }

            FreshStatus();
            uC_ExcData1.Load();

            btnIonBarPass.EEnabled = Kernel.OP.Level > 0;

            if (frmManual == null)
            {
                frmManual = new FormManual();
            }

            iRefresh++;
            if (iRefresh >= 40)
            {
                iRefresh = 0;
                GC.Collect();
            }
        }

        IOView frmIOView;
        RTCView frmRTCView;
        FormManual frmManual;
        FormChipData frmChipData_CV1;
        FormChipData frmChipData_CV2;
        FormChipData frmChipData_Insp1;
        FormChipData frmChipData_Insp2;
        FormChipData frmChipData_Insp3;
        FormChipData frmChipData_Insp4;
        private void btn_Switch_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            string[] info = btn.Tag.ToString().Split('|');
            switch (info[1])
            {
                #region 主操作
                case "Auto":    //自动
                    {
                        if (!ProcedureHelper_EQ.Door_Lock)
                        {
                            if (DialogResult.OK == MessageBox.Show("请确认门是否全部关闭锁上？", "询问", MessageBoxButtons.OK, MessageBoxIcon.Question))
                            {
                                if (Kernel.Exc.DI.X0E4_Door1 == 1 && Kernel.Exc.DI.X0E5_Door2 == 1 && Kernel.Exc.DI.X0E6_Door3 == 1 && Kernel.Exc.DI.X0E7_Door4 == 1 )
                                {
                                    ProcedureHelper_EQ.Door_ToLock = true;
                                    ProcedureHelper_Exc.SafeDoor1_ToLockk = true;
                                }
                                else
                                {
                                    MessageBox.Show("请确认机台门是否全部关闭？", "询问", MessageBoxButtons.OK, MessageBoxIcon.Question);
                                }
                            }
                            else
                            {
                                return;
                            }
                        }

                        ProcedureHelper_Exc.PresenceUpdate = true;

                        ProcedureHelper_EQ.ToAuto_BT = true;
                    }
                    break;
                case "Manual":  //手动
                    {
                        if (ProcedureHelper_EQ.ManualMode)
                        {
                            if (frmManual == null)
                            {
                                frmManual = new FormManual();
                            }
                            frmManual.ShowForm();
                        }
                        else
                        {

                        }
                        ProcedureHelper_EQ.ToManual_BT = true;
                    }
                    break;
                case "Init":    //初始化
                    {
                        if (ProcedureHelper_EQ.ManualMode)
                        {
                            if (DialogResult.OK == MessageBox.Show("请确认机台是否切到自动模式？", "询问", MessageBoxButtons.OK, MessageBoxIcon.Question))
                            {
                                ProcedureHelper_EQ.ToAuto_BT = true;
                                ProcedureHelper_EQ.ToInit_BT = true;
                            }
                        }
                        else
                        {
                            if (DialogResult.Yes == MessageBox.Show("机台是否执行初始化？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                            {
                                ProcedureHelper_EQ.ToInit_BT = true;
                            }
                        }
                    }
                    break;
                case "Run":     //自动运行
                    {
                        if (ProcedureHelper_EQ.ManualMode)
                        {
                            if (DialogResult.OK == MessageBox.Show("请确认机台是否切到自动模式？", "询问", MessageBoxButtons.OK, MessageBoxIcon.Question))
                            {

                            }
                        }
                        else
                        {
                            if (!ProcedureHelper_EQ.HomeComp)
                            {
                                MessageBox.Show("请确认机台是否全轴复归？", "询问", MessageBoxButtons.OK, MessageBoxIcon.Question);
                            }
                            else
                            {
                                ProcedureHelper_EQ.ToAutoRun_BT = true;
                            }
                        }
                    }
                    break;
                case "Stop":    //停止
                    {
                        ProcedureHelper_EQ.ToStop_BT = true;
                        ProcedureHelper_EQ.ToStop_BT_ForceStop = true;
                    }
                    break;
                case "InPutStop":    //停止入料
                    {
                        ProcedureHelper_EQ.InPutStop = !ProcedureHelper_EQ.InPutStop;
                    }
                    break;
                case "DryRun":    //空运转
                    {
                       ProcedureHelper_EQ.ToDryRun_BT = true;                       
                        
                    }
                    break;
                case "DoorLock"://门锁
                    {  if(Kernel.Exc.DI.X058_DoorMonitor1 == 1 && Kernel.Exc.DI.X059_DoorMonitor2 == 1 )
                        {
                            ProcedureHelper_EQ.Door_ToLock = true;
                            ProcedureHelper_Exc.SafeDoor1_ToULock = false;
                            ProcedureHelper_Exc.SafeDoor1_ToLockk = true;
                            ProcedureHelper_Exc.SafeDoor2_ToULock = false;
                            ProcedureHelper_Exc.SafeDoor2_ToLockk = true;
                        }
                        else
                        {
                            MessageBox.Show("请确认机台门是否全部关闭？", "询问", MessageBoxButtons.OK, MessageBoxIcon.Question);
                        }
                    }
                    break;
                case "DoorUnlock":
                    {
                        if (!ProcedureHelper_EQ.ManualMode)
                        {
                            if (DialogResult.OK == MessageBox.Show("请确认机台是否切到手动模式？", "询问", MessageBoxButtons.OK, MessageBoxIcon.Question))
                            {

                            }
                        }
                        else
                        {
                            ProcedureHelper_EQ.Door_ToLock = false;
                            ProcedureHelper_EQ.Door_ToUnlock = true;

                            ProcedureHelper_Exc.SafeDoor1_ToULock = true;
                            ProcedureHelper_Exc.SafeDoor1_ToLockk = false;
                            ProcedureHelper_Exc.SafeDoor2_ToULock = true;
                            ProcedureHelper_Exc.SafeDoor2_ToLockk = false;

                        }
                    }
                    break;
                case "Light":
                    {

                    }
                    break;
                case "Exit":
                    {
                        DialogResult dr = MessageBox.Show("确认退出？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (dr == System.Windows.Forms.DialogResult.No)
                        {
                            return;
                        }

                        this.Close();
                        Application.Exit();
                        //Environment.Exit(0);
                        Process.GetCurrentProcess().Kill();
                    }
                    break;
                case "Reset":
                    {
                        Task.Run(() =>
                        {
                            Kernel.motion.CV1_Driver.ResetError();
                            Kernel.motion.CV1_TrackSW_Y.ResetError();
                            Kernel.motion.CV1_Y.ResetError();
                            Kernel.motion.CV2_Driver.ResetError();
                            Kernel.motion.CV2_TrackSW_Y.ResetError();
                            Kernel.motion.CV2_Y.ResetError();
                            Kernel.motion.CCD1_X.ResetError();
                            Kernel.motion.CCD1_Y.ResetError();
                            Kernel.motion.CCD1_Z.ResetError();
                            Kernel.motion.CCD2_X.ResetError();
                            Kernel.motion.CCD2_Y.ResetError();
                            Kernel.motion.CCD2_Z.ResetError();
                            Kernel.motion.Insp1_CV1.ResetError();
                            Kernel.motion.Insp1_CV2.ResetError();
                            Kernel.motion.Insp1_Y.ResetError();
                            //Kernel.motion.Insp1_RM_Z.ResetError();
                            Kernel.motion.Insp2_CV1.ResetError();
                            Kernel.motion.Insp2_CV2.ResetError();
                            Kernel.motion.Insp2_Y.ResetError();
                            //Kernel.motion.Insp2_RM_Z.ResetError();
                            Kernel.motion.Insp3_CV1.ResetError();
                            Kernel.motion.Insp3_CV2.ResetError();
                            Kernel.motion.Insp3_Y.ResetError();
                            //Kernel.motion.Insp3_RM_Z.ResetError();
                            Kernel.motion.Insp4_CV1.ResetError();
                            Kernel.motion.Insp4_CV2.ResetError();
                            Kernel.motion.Insp4_Y.ResetError();
                            //Kernel.motion.Insp4_RM_Z.ResetError();

                            //if (Kernel.motion.LaserST_R.axis.State != Advantech.Motion.AxisState.STA_AX_READY)
                            //{
                            //    Kernel.motion.LaserST_R.ResetError();
                            //}
                        });

                        if (ProcedureHelper_EQ.ManualMode)
                        {
                            string cmd = "ErrorClear";
                            Kernel.Exc.Laser1.SQ_SendCMD.Enqueue(new KeyenceHelper.CtrlCMD(KeyenceHelper.CtrlCMD.typeMode.WX, cmd));
                        }
                    }
                    break;
                case "BuzzerStop":
                    {
                        ProcedureHelper_EQ.StopBuzzer = !ProcedureHelper_EQ.StopBuzzer;
                    }
                    break;
                #endregion

                #region 在席
             
                case "CV1":
                    {
                        if (frmChipData_CV1 == null)
                        {
                            frmChipData_CV1 = new FormChipData();
                        }
                        frmChipData_CV1.ShowForm(1, ParameterHelper.CV1);
                    }
                    break;
                case "CV2":
                    {
                        if (frmChipData_CV2 == null)
                        {
                            frmChipData_CV2 = new FormChipData();
                        }
                        frmChipData_CV2.ShowForm(2, ParameterHelper.CV2);
                    }
                    break;
                case "Insp1":
                    {
                        if (frmChipData_Insp1 == null)
                        {
                            frmChipData_Insp1 = new FormChipData();
                        }
                        frmChipData_Insp1.ShowForm(3, ParameterHelper.Insp1);
                    }
                    break;
                case "Insp2":
                    {
                        if (frmChipData_Insp2 == null)
                        {
                            frmChipData_Insp2 = new FormChipData();
                        }
                        frmChipData_Insp2.ShowForm(4, ParameterHelper.Insp2);
                    }
                    break;
                case "Insp3":
                    {
                        if (frmChipData_Insp3 == null)
                        {
                            frmChipData_Insp3 = new FormChipData();
                        }
                        frmChipData_Insp3.ShowForm(5, ParameterHelper.Insp3);
                    }
                    break;
                case "Insp4":
                    {
                        if (frmChipData_Insp4 == null)
                        {
                            frmChipData_Insp4 = new FormChipData();
                        }
                        frmChipData_Insp4.ShowForm(6, ParameterHelper.Insp4);
                    }
                    break;
                    #endregion
            }
        }
        private void GetControls(Control.ControlCollection ctrls, bool getAll = true)
        {
            foreach (Control item in ctrls)
            {
                if (item is Button && item.Tag?.ToString().Split('|')[0] == "btn")
                {
                    ((Button)item).Click += new EventHandler(this.btn_Switch_Click);
                }

                if (item is DLLPC.PCAP.PCButton && item.Tag?.ToString().Split('|')[0] == "btn")
                {
                    ((DLLPC.PCAP.PCButton)item).OP = Kernel.OP;
                }

                if (item.Controls != null && getAll)
                {
                    GetControls(item.Controls);
                }
            }
        }

        bool resetDelayOff = false;
        private void FreshStatus()
        {
            Kernel.OP.OPRec = true;
            btnAuto.Monitor(!ProcedureHelper_EQ.ManualMode);
            btnManual.Monitor(ProcedureHelper_EQ.ManualMode);
            btnInPutStop.Monitor(ProcedureHelper_EQ.InPutStop);
            btnInit.Monitor((PulseOn.Pulse_1s && ProcedureHelper_EQ.InitMode) || ProcedureHelper_EQ.HomeComp);
            btnRun.Monitor(ProcedureHelper_EQ.AutoMode);
            btnDryRun.Monitor(ProcedureHelper_EQ.DryRunMode);
            btnStop.Monitor((!ProcedureHelper_EQ.AutoMode && !ProcedureHelper_EQ.InitMode && ((PulseOn.Pulse_1s  && !ProcedureHelper_EQ.AllAxisStop) ||  ProcedureHelper_EQ.AllAxisStop)) || ProcedureHelper_EQ.ManualMode);
            //ProcedureHelper_EQ.ToStop_BT = btnStop.Monitor(false);
            //ProcedureHelper_EQ.Door_Lock = btnDoorLock.Monitor(ProcedureHelper_EQ.Door_Lock);

            btnDoorLock.Monitor(ProcedureHelper_EQ.Door_Lock);
            btnDoorUnlock.Monitor(!ProcedureHelper_EQ.Door_Lock, ProcedureHelper_EQ.ManualMode);
            btnLight.Monitor(ProcedureHelper_EQ.Light_Open);

            lblCurRecipe.Text = ParameterHelper.CurParam.PRM_Name;
            //btnCV1.BackColor = WorkDataStatus(ParameterHelper.CV1.Enable, Kernel.Exc.DI.X021_CV1_Stop == 1);
            //btnCV2.BackColor = WorkDataStatus(ParameterHelper.CV2.Enable, Kernel.Exc.DI.X027_CV2_Stop == 1);
            //btnInsp1.BackColor = WorkDataStatus(ParameterHelper.Insp1.Enable, Kernel.Exc.DI.X037_1_InspStage_Stop == 1);
            //btnInsp2.BackColor = WorkDataStatus(ParameterHelper.Insp2.Enable, Kernel.Exc.DI.X03F_2_InspStage_Stop == 1);
            //btnInsp3.BackColor = WorkDataStatus(ParameterHelper.Insp3.Enable, Kernel.Exc.DI.X047_3_InspStage_Stop == 1);
            //btnInsp4.BackColor = WorkDataStatus(ParameterHelper.Insp4.Enable, Kernel.Exc.DI.X04F_4_InspStage_Stop == 1);

            //btnCV1.Text = ParameterHelper.RBUpper.Wafer_ID;
            //btnCV2.Text = ParameterHelper.RBLower.Wafer_ID;
            //btnRotateST.Text = ParameterHelper.RotateST.Wafer_ID;

            if (ProcedureHelper_EQ.AutoMode)
            {
                lblStatus.Text = "运转中";
            }
            else if (!ProcedureHelper_EQ.ManualMode)
            {
                lblStatus.Text = "自动";
            }
            else if (ProcedureHelper_EQ.ManualMode)
            {
                lblStatus.Text = "手动";
            }
            else
            {
                lblStatus.Text = "初始化";
            }

            //报警复位至少ON 1个周期以上，确保其他线程执行到位
            if (ProcedureHelper_EQ.EQ_Reset)
            {
                if (resetDelayOff)
                {
                    ProcedureHelper_EQ.EQ_Reset = btnReset.Monitor(false);
                }
                resetDelayOff = true;
            }
            else
            {
                ProcedureHelper_EQ.EQ_Reset = btnReset.Monitor(false);
                resetDelayOff = false;
            }

            btnBuzzerStop.Monitor(ProcedureHelper_EQ.StopBuzzer);

            //if (ProcedureHelper_Insp.WaferLoad)
            //{
            //    ProcedureHelper_Insp.WaferLoad = false;

            //    string strWaferID = "";
            //    if (!ParameterHelper.TrainParam.WfInfo.MapSource)    //共用
            //    {
            //        strWaferID = ParameterHelper.CurParam.PRM_Name;
            //    }
            //    else    //单独
            //    {
            //        strWaferID = ParameterHelper.InspST.Wafer_ID;
            //    }

            //    if (!string.IsNullOrEmpty(strWaferID) && WaferMapHelper.LoadWaferData(strWaferID))
            //    {
            //        uC_WaferShow1.ShowForm(Kernel.StageWf);
            //    }
            //}


            //btnIonBarPass.Monitor(ProcedureHelper_EQ.IonAlarmPass && btnIonBarPass.Enabled, ProcedureHelper_EQ.ManualMode);
        }

        /// <summary>
        /// 显示在席颜色
        /// </summary>
        /// <param name="DataEnable">软件在席</param>
        /// <param name="Exist">硬体在席</param>
        /// <returns>在席颜色</returns>
        private Color WorkDataStatus(bool DataEnable, bool Exist)
        {
            Color myColor;
            if (DataEnable && Exist)
            {
                myColor = Color.Green;
            }
            else
            {
                if (!DataEnable && !Exist)
                {
                    myColor = Color.White;
                }
                else
                {
                    myColor = (DataEnable) ? Color.Red : Color.Yellow;
                }
            }
            return myColor;
        }

        private void tbxLaserID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                ActiveControl = null;
            }
        }
        private void btnIonBarPass_Click(object sender, EventArgs e)
        {
            ProcedureHelper_EQ.IonAlarmPass = !ProcedureHelper_EQ.IonAlarmPass;
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(@"D:\Img\");
            System.IO.FileInfo[] fileArrays = dirInfo.GetFiles();

            List<HalconDotNet.HImage> lsImgs = new List<HalconDotNet.HImage>();

            for (int i = 0; i < fileArrays.Length; i++)
            {
                HalconDotNet.HImage himg = new HalconDotNet.HImage(fileArrays[i].FullName);
                lsImgs.Add(himg);
            }

            double dTime = 0;


            //cImg.WriteImage("jpg", 0, "D:\\b12212.jpg");

            //for (int i = 0; i < 100; i++)
            //{
            //    string filePath = string.Format(@"D:\Img1\"+ i.ToString(""))
            //}
        }
    }
}
